from ncclient import manager
import xml.etree.ElementTree as ET

def get_route(ip,username,password,port='830'):
    payload = """
    <filter xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
      <routing-state xmlns="urn:ietf:params:xml:ns:yang:ietf-routing">
        <routing-instance>
          <ribs>
            <rib>
              <routes>
                <route/>
              </routes>
            </rib>
          </ribs>
        </routing-instance>
      </routing-state>
    </filter>
    """

    with manager.connect(host=ip,
                         port=port,
                         username=username,
                         password=password,
                         timeout=90,
                         hostkey_verify=False,
                         device_params={'name': 'csr'}) as m:

        try:
            response = m.get(payload).xml
            root = ET.fromstring(response)
            route_table = []
            for x in root.iter('{urn:ietf:params:xml:ns:yang:ietf-routing}route'):
                route = []
                for y in x:
                    if y.tag == '{urn:ietf:params:xml:ns:yang:ietf-routing}next-hop':
                        for z in y:
                            if z.tag == '{urn:ietf:params:xml:ns:yang:ietf-routing}next-hop-address':
                                route.append(z.text)
                    else:
                        route.append(y.text)
                route_table.append(route)
        except Exception as e:
            print(e)
    return route_table
if __name__ == '__main__':
        route_table = get_route('172.16.1.212','admin','Cisc0123')
        for route in route_table:
            print('%-20s  via %-20s  type %s' % (route[0],route[3],route[4]))


